﻿using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Extensions.Configuration;
using SenderSerilog.Code;
using Serilog;
using Serilog.Core;
using Serilog.Events;

namespace SenderSerilog
{
    class Program
    {
        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .AddInMemoryCollection(new[]
                {
                    new KeyValuePair<string, string>("apiKey", "secret-api-key")
                })
                .Build();

            Log.Logger = new LoggerConfiguration()
                // 将配置传给 Serilog 的提供程序 
                //.ReadFrom.Configuration(Configuration)
                .Enrich.With(new DateTimeNowEnricher())

                .MinimumLevel.Information()//最小记录级别

                .Enrich.FromLogContext()//记录相关上下文信息 
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)//对其他日志进行重写,除此之外,目前框架只有微软自带的日志组件
                                                                              //.WriteTo.Console()//输出到控制台 //.WriteTo.File
                .WriteTo.Http(
                    requestUri: "http://localhost:20711/api/log/recode",
                    queueLimitBytes: null,
                    httpClient: new CustomHttpClient(),
                    configuration: configuration)

                .WriteTo.Async(o =>
                {
                    o.Console();
                    o.File("logs/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/log_.log", restrictedToMinimumLevel: LogEventLevel.Error, rollingInterval: RollingInterval.Day); //输出到文件,需要提供输出路径和周期
                })
                .CreateLogger();



            int num = 0;
            while (true)
            {
                LogHelper.LogVerbose("测试LogVerbose"+num, sender: "zhangsan", version: "1.2.3.0", exceptionName: "测试异常"+num);
                LogHelper.LogInformation("测试LogInformation" + num);
                LogHelper.LogDebug("测试LogDebug" + num, sender: "zhangsan", version: "1.2.3.0", exceptionName: "测试异常"+num);
                LogHelper.LogWarning("测试LogWarning" + num, sender: "zhangsan", version: "1.2.3.0", exceptionName: "测试异常"+num);
                LogHelper.LogError("测试LogError" + num, sender: "zhangsan", version: "1.2.3.0", exceptionName: "测试异常"+num);
                LogHelper.LogFatal("测试LogFatal" + num, sender: "zhangsan", version: "1.2.3.0", exceptionName: "测试异常"+num);
                num++;
                Thread.CurrentThread.Join(3000); //每3秒发送日志
            }
          
        }

        #region Serilog 相关设置
        class DateTimeNowEnricher : ILogEventEnricher
        {
            public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                    "DateTimeNow", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
        }

        #endregion

    }
}
